'''
Contact form allows users to send email messages through an interface
'''

from django import forms
from django.core.mail import send_mail
from django.conf import settings
from django.template import loader, RequestContext
from django.contrib.sites.models import Site

attrs_dict = { 'class': 'required' }

class ContactForm(forms.Form):
    '''
    Base contact form class
    '''
    def __init__(self, data=None, request=None, *args, **kwargs):
        if request is None:
            raise TypeError('Argument "request" must be supplied')
        super(ContactForm, self).__init__(data, *args, **kwargs)
        self.request = request

    name = forms.CharField(max_length=50,
                            widget=forms.TextInput(attrs=attrs_dict),
                            label=u'Your Name')

    email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict,
                                                                max_length=100)),
                                label=u'Your Email Address')

    subject = forms.CharField(widget=forms.TextInput(attrs=attrs_dict),
                                label=u'Subject')

    message = forms.CharField(widget=forms.Textarea(attrs=attrs_dict),
                            label=u'Message')

    from_email = settings.DEFAULT_FROM_EMAIL

    recipient_list = [tuple[1] for tuple in settings.MANAGERS]

    template_name = 'contact/contact.txt'

    def get_message_dict(self):
        '''
        Collects ``from_email``, ``message``, ``recipient_list``, and ``subject`` into a dictionary
        '''
        if not self.is_valid():
            raise ValueError('Message cannot be sent with invalid form')
        message_dict = {}
        formdata = getattr(self, "cleaned_data",
                                   getattr(self, "clean_data", None))
        subject=formdata['subject']
        message_dict['subject'] = callable(subject) and subject() or subject
        message=formdata['name'] + '\n' +formdata['email'] + '\n' + formdata['message']
        message_dict['message'] = callable(message) and message() or message
        for m in ( 'from_email', 'recipient_list'):
            attr = getattr(self, m)
            message_dict[m] = callable(attr) and attr() or attr
        return message_dict

    def send(self, fail_silently=False):
        '''
        Build and send the message through email
        ``send_mail`` calls ``get_message_dict`` to get keyword arguments
        '''
        send_mail(fail_silently=fail_silently, **self.get_message_dict())
